import jinja2, os, webapp2, urllib, cgi
from google.appengine.ext import db
from google.appengine.api import mail, users
import displugged
from displugged import navbar
from datatypes import *
import sessions

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))

class create(webapp2.RequestHandler):
    def get(self):
        if not sessions.isRegistered():
            self.redirect('/')
            return
        template = jinja_environment.get_template('dynamic/makeoffer.html')
        self.response.out.write(template.render({'navbar': navbar(self),
                                                 'create_edit': 'Create',
                                                 'title':'Title',
                                                 'subject':'Subject'}))
        
    def post(self):
        if not sessions.isRegistered():
            self.redirect("/signup")
            return        
        current_user = sessions.ourUserModel()

        title = self.request.get("title")
        subject = self.request.get("subject")
        price = self.request.get("price")
        description = self.request.get("description")
        tags = self.request.get("tags")
        newOffer = TutorOffer(parent = OfferPathGen())
        newOffer.tutor = current_user
        newOffer.subject = subject
        newOffer.title = title
        newOffer.description = db.Text(description)
        newOffer.price = int(price) #error checking might be helpful

        ##Deal with tags
        tags = tags.split(',')
        tags = [x.strip().lower() for x in tags]
        newOffer.tags = tags
        
        newOffer.put()


        processTags(tags, newOffer)

        self.response.out.write("Your offer has been listed.")

class search(webapp2.RequestHandler):
    def get(self):
        template = jinja_environment.get_template('dynamic/searchresults.html')
        self.response.out.write(template.render({'navbar': navbar(self)}))
        
    def post(self):
        template = jinja_environment.get_template('dynamic/searchresults.html')
        current_user = users.get_current_user()
        query = self.request.get("query")
        results = TutorOffer.all().ancestor(OfferPathGen()
                    ).filter('title =', query)
        self.response.out.write(template.render({'navbar': navbar(self),
                                                 'results': results}))

class listing(webapp2.RequestHandler):
    def get(self):
        key = self.request.get("id")
        try:
            result = db.get(key)
        except:
            displugged.giveError(self, "Oops! Looks like this is a bad link.")
            return
        self.response.out.write("<h1>%s</h1>"%result.title)
        self.response.out.write("<br /><h5>%s</h5>"%result.subject)
        self.response.out.write("<br /><b>Price: </b>"+str(result.price))
        self.response.out.write("<br /><br /><b>Description:</b><br />"+result.description)
        listing = db.get(key)
        currentUser = sessions.ourUserModel()
        if listing.tutor.key() == currentUser.key():
            self.response.out.write("<br /><br /><a href='/offer/edit?id=%s'>Edit</a>"%key)
            self.response.out.write("<br /><br /><a href='/offer/delete?id=%s'>Delete</a>"%key)
        else:
            self.response.out.write("<br /><br /><a href='/communicate/send?sendto=%s'>Contact Tutor</a>"%listing.tutor.key())
class delete(webapp2.RequestHandler):
    def get(self):
        key = self.request.get("id")
        listing = db.get(key)
        currentUser = sessions.ourUserModel()
        if listing.tutor.key() == currentUser.key():
            listing.delete()

class edit(webapp2.RequestHandler):
    def get(self):
        if not sessions.isRegistered():
            self.redirect('/')
            return
        currentUser = sessions.ourUserModel()
        template = jinja_environment.get_template('dynamic/makeoffer.html')
        editid = self.request.get("id")
        try:
            toedit = db.get(editid)
        except:
            self.response.out.write("Oops! Looks like this is a bad link.")
            return
        if toedit.tutor.key() == currentUser.key(): 
            self.response.out.write(template.render({'navbar': navbar(self),
                                                 'create_edit':'Edit',
                                                 'title':toedit.title,
                                                 'subject':toedit.subject,
                                                 'price':toedit.price,
                                                 'description':toedit.description,
                                                 'tags':','.join(toedit.tags),
                                                 'hidden':editid}))
        else:
            self.response.out.write("Doesn't look like you have the permissions to edit this listing.")
    def post(self):
        currentUser = sessions.ourUserModel()
        editid = self.request.get("editid")
        try:
            editOffer = db.get(editid)
        except:
            displugged.giveError(self, "Oops! Looks like this is a bad link.")
        if editOffer.tutor.key() == currentUser.key(): 
            title = self.request.get("title")
            subject = self.request.get("subject")
            price = self.request.get("price")
            description = self.request.get("description")
            tags = self.request.get("tags")
            editOffer.subject = subject
            editOffer.title = title
            editOffer.description = db.Text(description)
            editOffer.price = int(price) #error checking might be helpful
            ##Deal with tags
            tags = tags.split(',')
            tags = [x.strip().lower() for x in tags]
            editOffer.tags = tags
            editOffer.put()
        else:
            self.response.out.write("Doesn't look like you have the permissions to edit this listing.")
        self.redirect('/offer/listing?id='+editid)
app = webapp2.WSGIApplication([('/offer/create', create),
                               ('/offer/search', search),
                               ('/offer/listing',listing),
                               ('/offer/delete', delete),
                               ('/offer/edit',edit)],
                              debug=True)
